package com.owen.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson2.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.owen.pojo.Fenlei;
import com.owen.server.FenleiServer;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@RequestMapping(value = "/fenlei")
@Controller
public class

FenleiController {

    @Autowired
    private FenleiServer fenleiServer;

    @ResponseBody
    @RequestMapping(value = "/fileExport")
    public void fileExport(Fenlei fenlei, HttpServletResponse response) throws ClassNotFoundException, IndexOutOfBoundsException, IOException {
        // 生成excel
        ExcelWriter writer = ExcelUtil.getWriter();
        // 数据库查询
        List<Fenlei> fenleis = fenleiServer.findByFenlei(fenlei);
        List<Map<String, Object>> rows = fenleis.stream().map(item -> {
            Map<String, Object> maps = new HashMap<>();
            maps.put("id", item.getId().toString());
            maps.put("fenleilock", item.getFenleilock());
            maps.put("name", item.getName());
            return maps;
        }).collect(Collectors.toList());


        // Title
        int columns = Class.forName("com.owen.pojo.Fenlei").getDeclaredFields().length;
        writer.merge(columns - 1, "商品信息");
        // Header
        writer.addHeaderAlias("id", "ID");
        writer.addHeaderAlias("fenleilock", "是否购买");
        writer.addHeaderAlias("name", "商品");
        // Body
        writer.setColumnWidth(0, 30);
        writer.setColumnWidth(1, 30);
        writer.setColumnWidth(2, 30);
        writer.write(rows, true);
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("商品信息-" + DateUtil.today() + ".xls", "utf-8"));
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        writer.close();
        IoUtil.close(out);
    }

    @ResponseBody
    @RequestMapping(value = "/find", method = RequestMethod.GET)
    public String findFenlei() {

        PageHelper.startPage(1, 10);
        List<Fenlei> fenlei = fenleiServer.findFenlei();
        PageInfo<Fenlei> pageInfo = new PageInfo<>(fenlei);

        Map<String, Object> res = new HashMap<>();
        if(fenlei != null){
            res.put("code", "200");
            res.put("msg", "查询成功");
            res.put("data", pageInfo);
        } else {
            res.put("code", "201");
            res.put("msg", "查询失败");
        }

        String json = JSON.toJSONString(res);
        return json;
    }

    @ResponseBody
    @RequestMapping(value = "/findAll", method = RequestMethod.GET)
    public String findAll() {

        Fenlei fenlei = new Fenlei();
        List<Fenlei> fenleis = fenleiServer.findByFenlei(fenlei);

        Map<String, Object> res = new HashMap<>();
        if(fenleis != null){
            res.put("code", "200");
            res.put("msg", "查询成功");
            res.put("data", fenleis);
        } else {
            res.put("code", "201");
            res.put("msg", "查询失败");
        }

        String json = JSON.toJSONString(res);
        return json;
    }

    @ResponseBody
    @RequestMapping(value = "/findByFenlei", method = RequestMethod.GET)
    public String findByFenlei(Fenlei fenlei, Integer xuanzhepage, Integer currentPage) {

        // 获取页数
        Integer current = 1;
            if (currentPage != null) {
                current = Integer.valueOf(currentPage);
            }

        PageHelper.startPage(current, xuanzhepage);
        List<Fenlei> fenleis = fenleiServer.findByFenlei(fenlei);
        PageInfo<Fenlei> pageInfo = new PageInfo<>(fenleis);

        Map<String, Object> res = new HashMap<>();
        if(fenlei != null){
            res.put("code", "200");
            res.put("msg", "查询成功");
            res.put("data", pageInfo);
        } else {
            res.put("code", "201");
            res.put("msg", "查询失败");
        }

        String json = JSON.toJSONString(res);
        return json;
    }

    @ResponseBody
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.POST)
    public String deleteBatch(Integer[] ids) {
        Map<String, Object> res = new HashMap<>();
        Integer count = fenleiServer.deleteBatch(ids);
        if (count > 0) {
            res.put("code", 200);
            res.put("msg", "删除成功！");
        } else {
            res.put("code", 201);
            res.put("msg", "删除失败！");
        }
        String json = JSON.toJSONString(res);
        return json;
    }

    @ResponseBody
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String find(@PathVariable("id") Long id) {
        Fenlei byId = fenleiServer.findById(id);
        Map<String, Object> res = new HashMap<>();
        res.put("code", "200");
        res.put("msg", "查询成功");
        res.put("data", byId);
        String json = JSON.toJSONString(res);
        return json;
    }

    @ResponseBody
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public String deleteById(@PathVariable("id") Long id) {
        Integer byId = fenleiServer.deleteById(id);
        Map<String, Object> res = new HashMap<>();
        if (Optional.ofNullable(byId).isPresent() && byId > 0) {
            res.put("code", "200");
            res.put("msg", "删除成功");
        } else {
            res.put("code", "201");
            res.put("msg", "删除失败");
        }
        String json = JSON.toJSONString(res);
        return json;
    }

    @ResponseBody
    @RequestMapping(value = "/addFenlei", method = RequestMethod.GET)
    public String addFenlei(Fenlei fenlei) {
        Integer integer = fenleiServer.addFenlei(fenlei);
        Map<String, Object> res = new HashMap<>();
        if (Optional.ofNullable(integer).isPresent() && integer > 0) {
            res.put("code", "200");
            res.put("msg", "新增成功");
        } else {
            res.put("code", "201");
            res.put("msg", "新增失败");
        }
        String json = JSON.toJSONString(res);
        return json;
    }

    @ResponseBody
    @RequestMapping(value = "/update")
    public String update(Fenlei fenlei) {
        Map<String, Object> res = new HashMap<>();
        Integer integer = fenleiServer.updateById(fenlei);
        if (integer == 0) {
            res.put("code", "201");
            res.put("msg", "修改成功");
        } else if (integer > 0) {
            res.put("code", "200");
            res.put("msg", "修改失败");
        }
        String json = JSON.toJSONString(res);
        return json;
    }

}
